package com.server;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;

import com.shared.QueueElement;
import com.shared.SystemMsg;

/**
 * This is the thread being used by the server to handle a particular user
 * sending messages.
 * 
 * @author jiafanz
 *
 */
public class ServerThread extends Thread
{
    private QueueHandler        queueHadnler;
    
    // the socket connected to our client.
    private QueueElement        queueElement;
    
    /**
     * Constructor of the ServerThread.
     * @param queueHadnler the QueueHandler that handles the queue.
     * @param queueElement the queue element that this thread belongs to.
     */
    public ServerThread(QueueHandler queueHadnler, QueueElement queueElement)
    {
        this.queueHadnler = queueHadnler;
        this.queueElement = queueElement;
        
        // start up this thread
        start();
    }
    
    /**
     * {@inheritDoc}
     */
    public void run()
    {
        try
        {
            // create a DataInputStream for communication; the client
            // is using a DataOutputStream to write to us
            DataInputStream din = new DataInputStream(
                    queueElement.getSocket().getInputStream());
            
            // over and over...
            while (true)
            {
                // read the next message...
                String message = din.readUTF();
                
                if (message.equalsIgnoreCase(SystemMsg.Disconnected.toString()))
                {
                    // return here will invoke the finally
                    return;
                }
                
                // tell the world
                System.out.println("Sending: " + message);
                
                // ... and have the queueHandler sent it to the pair listener
                queueHadnler.sendMsgToPairElement(queueElement, message);
            }
        }
        catch (EOFException ie)
        {
            // we don't need an error message for this
            // JIAFANZ: check the reason for this.
        }
        catch (IOException ex)
        {
            if (!queueElement.getSocket().isClosed())
            {
                ex.printStackTrace();                
            }
        }
        finally
        {
            // The connection is closed for one reason or another,
            // so we have to let the server dealing with it.
            queueHadnler.removeConnection(queueElement);
        }
    }
}
